package com.shenfc.fxzj.resolver;

import com.shenfc.fxzj.editor.DateEditor;
import com.shenfc.fxzj.editor.NumberEditor;
import com.shenfc.fxzj.util.HtmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.shenfc.fxzj.constants.CodeConstants.MSG;
import static com.shenfc.fxzj.constants.CodeConstants.SUCCESS;

/**
 * 异常解析器
 */
@ControllerAdvice
@Slf4j
public class ExceptionResolver {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor());
        binder.registerCustomEditor(int.class, new NumberEditor());
    }
    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
//    @ModelAttribute
//    public void addAttributes(Model model) {
//        model.addAttribute("author", "Magical Sam");
//    }
    /**
     * 异常分类处理
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        ModelAndView modelAndView =new ModelAndView();
        if(ex instanceof UnauthorizedException){
            modelAndView.addObject("type","1");
            modelAndView.setViewName("err");
            return modelAndView;
        }
        jsonMap.put(SUCCESS,false);
        jsonMap.put(MSG,"控制层报错---请求地址:"+request.getRequestURI()+"---报错原因："+ ex.getMessage());
        HtmlUtil.writerJson(response,jsonMap);
        log.error("控制层报错---请求地址:"+request.getRequestURI(), ex);
        return null;
    }

}
